package com.zt.bigdata.practise.javastrategy.chapter7;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * File
 */
public class Chapter7 {
    public static void main(String[] args) throws Exception {
        //7.1 文件处理
        try (Stream<String> lines = Files.lines(Paths.get("/Users/zhangtong/IdeaProjects/hangy/zhangtong/springcloud/allin/test/practise/src/main/resources/file.txt"));) {
            lines.filter(s -> s.length() > 10)
                    .sorted(Comparator.comparingInt(String::length).reversed())
                    .limit(10)
                    .forEach(w -> System.out.printf("%s (%d)%n", w, w.length()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (Stream<String> lines = Files.lines(Paths.get("/Users/zhangtong/IdeaProjects/hangy/zhangtong/springcloud/allin/test/practise/src/main/resources/file.txt"));) {
            Map<Integer, Long> map = lines.filter(s -> s.length() > 10)
                    .sorted(Comparator.comparingInt(String::length).reversed())
                    .collect(Collectors.groupingBy(String::length, Collectors.counting()));
            map.entrySet().stream()
                    .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
                    .forEach(e -> System.out.printf("Length %d: %d words%n",
                            e.getKey(), e.getValue()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (Stream<String> lines = new BufferedReader(
                new FileReader("/usr/share/dict/words")).lines()) {

        } catch (IOException e) {
            e.printStackTrace();
        }
        //7.2 以流的形式检索文件

        try (Stream<Path> list = Files.list(Paths.get("/Users/zhangtong/IdeaProjects/hangy/zhangtong/springcloud/allin/test/practise/src/main/resources"))) {
            list.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (Stream<Path> paths = Files.walk(Paths.get("/Users/zhangtong/IdeaProjects/hangy/zhangtong/springcloud/allin/test/practise/src/main"))) {
            paths.filter(path -> path.toFile().getName().endsWith(".java"))
                    .forEach(path -> System.out.println(path.getFileName()));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
